const { Op, Quest, Scorelimit, Option, Childoption, User, Userquest, Result, Questtype, Optiontype } = require('../models')
const { join, keySort } = require('../utils/join')
const qr = require('qr-image')

//后台首页
let home_g = async ctx => {

    if (ctx.session.username !== 'admin') return ctx.status = 404

    //判断问卷是否过了截止时间
    let quest = await Quest.findAll({
        where: {
            questStateId: 1,
            deadline: {
                [Op.ne]: null,
                [Op.lt]: Date.now(),
            }
        }
    })

    let obj = JSON.parse(JSON.stringify(quest));

    if (obj) {
        obj.forEach(async item => {
            // console.log('有内容要更新');
            // console.log(item);
            await Quest.update({ questStateId: 2 }, { where: { id: item.id } })
        })
    }

    ctx.render('index.html')
}
//个人中心
let adminCenter_g = async ctx => {
    ctx.render('adminCenter.html')
}
//修改密码
let uppwdVtr_p = async ctx => {
    let { oldpwd, newpwd } = ctx.request.body;

    if (oldpwd.trim() && newpwd.trim()) {
        let user = await User.findOne({ where: { id: ctx.session.id } })

        if (user.getDataValue('pwd') !== oldpwd) return ctx.body = { err: 423, msg: '错误，旧密码错误！！' }

        await User.update({ pwd: newpwd }, { where: { id: ctx.session.id } })

        ctx.body = { code: 200, msg: '修改成功' }
    } else {
        ctx.body = { err: 234, msg: '错误，请输入新旧密码！！' }
    }
}


/* 开启的问卷
{
    id: 1,
    TypeId:0,
    type:'评分问卷'
    title: '调查调查',
    remark: '说明写点什么呢',
    optionCount: 10,
    writeCount: 40,
    state: 1,
    createTime: '2021-5-15',
    endTime: '2021-5-20',
    url: 'https://wj.qq.com/s2/8507983/1' 
}
*/
let startQuest_g = async ctx => {
    let obj = await join({
        attributes: ['id', 'code', 'questTypeId', 'questName', 'remarks', 'deadline', 'createAt'],
        where: {
            isDeleted: '0',
            questStateId: 1,
        },
        include: [
            {
                model: Option,
                attributes: ['id', 'content']
            },
            {
                model: Userquest,
                attributes: ['id', 'questId']
            }, {
                model: Questtype,
                attributes: ['typeName']
            }
        ],
        order: [['id', 'desc']]
    })


    let list = JSON.parse(JSON.stringify(obj))

    let result = []
    list.rows.forEach(item => {
        result.push({
            id: item.id,
            TypeId: item.questTypeId,
            type: item.questtype.typeName,
            title: item.questName,
            remark: item.remarks,
            optionCount: item.options.length,
            writeCount: item.userquests.length,
            state: 1,
            createTime: new Date(parseInt(item.createAt)).get()['date'],
            endTime: item.deadline === null ? null : new Date(parseInt(item.deadline)).get()['date'],
            url: 'http://localhost:3500/quest/writequest/' + item.code
        })
    })


    ctx.body = result


}
/*  关闭的问卷
 
{
    id: 1,
    TypeId:0,
    type:'评分问卷'
    title: '调查调查',
    remark: '说明写点什么呢',
    optionCount: 10,
    writeCount: 40,
    state: 2,
    createTime: '2021-5-15',
    endTime: '2021-5-20'
}
*/
let stopQuest_g = async ctx => {
    let obj = await join({
        attributes: ['id', 'questTypeId', 'questName', 'remarks', 'deadline', 'createAt'],
        where: {
            isDeleted: '0',
            questStateId: 2
        },
        include: [
            {
                model: Option,
                attributes: ['id', 'content']
            },
            {
                model: Userquest,
                attributes: ['id', 'questId']
            }, {
                model: Questtype,
                attributes: ['typeName']
            }
        ],
        order: [['id', 'desc']]
    })
    let list = JSON.parse(JSON.stringify(obj))


    let result = []
    list.rows.forEach(item => {
        result.push({
            id: item.id,
            TypeId: item.questTypeId,
            type: item.questtype.typeName,
            title: item.questName,
            remark: item.remarks,
            optionCount: item.options.length,
            writeCount: item.userquests.length,
            state: 2,
            createTime: new Date(parseInt(item.createAt)).get()['date'],
            endTime: item.deadline === null ? null : new Date(parseInt(item.deadline)).get()['date']
        })
    })

    // console.log(result);
    ctx.body = result
}
/* 待发布的问卷
{
    id: 1,
    title: '',
    type:'',
    remark:'',
    optionCount: '',
    state: '',
    createTime: ''
  } */
let saveQuest_g = async ctx => {
    let obj = await join({
        attributes: ['id', 'questName', 'questTypeId', 'remarks', 'createAt'],
        where: {
            isDeleted: '0',
            questStateId: 3
        },
        include: [
            {
                model: Option,
                attributes: ['id', 'content']
            }, {
                model: Questtype,
                attributes: ['typeName']
            }
        ],
        order: [['id', 'desc']]
    })
    let list = JSON.parse(JSON.stringify(obj))


    let result = []
    list.rows.forEach(item => {
        // console.log('请求的问卷id', item.questTypeId);
        result.push({
            id: item.id,
            typeId: item.questTypeId,
            type: item.questtype.typeName,
            title: item.questName,
            remark: item.remarks,
            optionCount: item.options.length,
            state: 3,
            createTime: new Date(parseInt(item.createAt)).get()['date']
        })
    })

    ctx.body = result
}

//关闭问卷
let closeQuest_p = async ctx => {
    let { questId } = ctx.request.body;

    if (parseInt(questId).toString() === 'NaN') return ctx.body = { err: 444, msg: '错误!' }

    let quest = await Quest.update({ questStateId: 2, deadline: Date.now() }, { where: { id: questId } })

    if (quest) {
        let obj = await join({
            attributes: ['id', 'questTypeId', 'questName', 'remarks', 'deadline', 'createAt'],
            where: {
                isDeleted: '0',
                id: questId
            },
            include: [
                {
                    model: Option,
                    attributes: ['id', 'content']
                },
                {
                    model: Userquest,
                    attributes: ['id', 'questId']
                }, {
                    model: Questtype,
                    attributes: ['typeName']
                }
            ],
            order: [['id', 'desc']]
        })
        let list = JSON.parse(JSON.stringify(obj))


        let result = []
        list.rows.forEach(item => {
            result.push({
                id: item.id,
                TypeId: item.questTypeId,
                type: item.questtype.typeName,
                title: item.questName,
                remark: item.remarks,
                optionCount: item.options.length,
                writeCount: item.userquests.length,
                state: 2,
                createTime: new Date(parseInt(item.createAt)).get()['date'],
                endTime: new Date().get()['date']
            })
        })

        ctx.body = { code: 200, msg: 'ok', data: result }
    } else {
        ctx.body = { err: 560, msg: '关闭失败' }
    }
}

//删除问卷
let deletedQuest_d = async ctx => {
    let { questId } = ctx.request.body;

    if (parseInt(questId).toString() === 'NaN') return ctx.body = { err: 444, msg: '错误!' }

    let quest = await Quest.update({ isDeleted: '1' }, { where: { id: questId } })

    if (quest) {
        ctx.body = { code: 200, msg: '删除成功', data: { id: questId } }
    }
    else {
        ctx.body = { err: 4001, msg: '删除失败' }
    }
}

//问卷调查数据分析

let questdataview_g = async ctx => {

    let { questId } = ctx.query;

    if (!questId) return ctx.body = { err: 99, msg: '参数错误' }

    let uqcount = await Userquest.count({ where: { questId: questId } })

    if (uqcount === 0) return ctx.body = { err: 42, msg: '当前还未有人填写问卷，无法查看' }

    let obj = await join({
        attributes: ['id', 'questName', 'questTypeId', 'questStateId', 'remarks'],
        where: {
            id: questId
        },
        include: [
            {
                model: Userquest,
                attributes: ['id', 'userId', 'questId'],
                include: [
                    {
                        model: User,
                        attributes: ['id', 'user']
                    },
                    {
                        model: Result,
                        attributes: ['id', 'content'],
                        include: [
                            {
                                model: Option,
                                attributes: ['id', 'content']
                            }
                        ]
                    }
                ]
            }

        ]
    })


    let uq = JSON.parse(JSON.stringify(obj)).rows[0]


    if (uq.questTypeId === 1) {//评分问卷

        let options = []
        let list = []

        let optionIdList = []
        uq.userquests.forEach(item => {

            let scoreList = []
            item.results.forEach(i => {
                options.push(i.option.content)
                optionIdList.push(i.option.id)
                scoreList.push(i.content)
            })
            list.push({
                id: item.id,
                user: item.user.user,
                results: scoreList
            })

        })

        let maxScoreList = []
        let minScoreList = []
        let aveScoreList = []
        let sumScoreList = []
        optionIdList = [...new Set(optionIdList)]


        for (let index = 0; index < optionIdList.length; index++) {
            let score = await Result.max('content', { where: { optionId: optionIdList[index] } })
            let score2 = await Result.min('content', { where: { optionId: optionIdList[index] } })
            let result = await Result.findAll({ where: { optionId: optionIdList[index] } })

            let arr = JSON.parse(JSON.stringify(result))
            let content = []
            arr.forEach(item => {
                content.push(item.content)
            })

            let sumscore = content.reduce((a, b) => parseInt(a) + parseInt(b))

            maxScoreList.push(score)
            minScoreList.push(score2)
            aveScoreList.push(sumscore / arr.length)
            sumScoreList.push(sumscore)
        }


        let tj = []
        maxScoreList.forEach((item, index) => {
            tj.push({
                title: [...new Set(options)][index],
                max: item,
                min: minScoreList[index],
                ave: aveScoreList[index].toFixed(2),
                sum: sumScoreList[index]
            })
        })

        ctx.render('wjrelt.html', { options: [...new Set(options)], list, tj })
        return;
    }

    // console.log(uq);

    // let user_b = uq.userquests[0].user
    // let result_b = uq.userquests[0].results

    /* 
    [
        {
            id:1,
            optionType:'单选',
            writeCount:10,
            title:'今天上班迟到了吗？'，
            texts:[],
            childOptions:[
                {
                    title:'当然没有,
                    takeCount:6,
                    proportion：30%
                },
                 {
                    title:'迟到了,
                    takeCount:3，
                     proportion：20%
                },
                {
                    title:'其他原因迟到了',
                    takeCount:1,
                     proportion：50%
                }

            ]
        }
    ]
    
    */
    let usercy = []
    uq.userquests.forEach(usquer => {

        let optionArr = [];
        let selectContent = []
        usquer.results.forEach(jgitem => {
            optionArr.push(jgitem.option)
            selectContent.push(jgitem.content)
        })
        usercy.push({
            optionArr,
            selectContent
        })

    })
    // console.log('usercy', usercy);

    let resultArr = []

    for (let j = 0; j < usercy[0].optionArr.length; j++) {
        let title = usercy[0].optionArr[j].content

        let childOptions = []
        let cdops = await Childoption.findAll({ where: { optionId: usercy[0].optionArr[j].id } })

        let cdopObj = JSON.parse(JSON.stringify(cdops));


        cdopObj.forEach(item => {
            childOptions.push({
                takeCount: 0,
                title: item.content
            })
        })



        // console.log('childOptions', childOptions);

        let optPId = await Option.findOne({ where: { id: usercy[0].optionArr[j].id } })
        let optionTypeName = await Optiontype.findOne({ where: { id: optPId.getDataValue('optionTypeId') } })

        let texts = []
        if (optionTypeName.getDataValue('typeName') === '文本') {
            usercy.forEach(item => {
                texts.push(item.selectContent[j])
            })
        }


        resultArr.push({
            optionType: optionTypeName.getDataValue('typeName'),
            writeCount: uq.userquests.length,
            title: title,
            texts: texts,
            childOptions
        })

    }

    // console.log('resultArr', resultArr);

    let contentStr = ''
    usercy.forEach(item => {

        item.selectContent.forEach(item2 => {
            contentStr += item2 + '^'
        })
    })




    resultArr.forEach((item, i) => {
        item.childOptions.forEach(item2 => {
            let num = 0;
            let index = contentStr.indexOf(item2.title)

            while (index !== -1) {
                num++;
                index = contentStr.indexOf(item2.title, index + 1)
            }
            item2.takeCount = num;
            item2.proportion = `${((num / item.writeCount) * 100).toFixed(1)}`;
        })
        item.id = i + 1;
    })


    // console.log('结果', resultArr);
    ctx.render('reltcommon.html', { resultArr })

}

//二维码动态生成

let createImage_g = async ctx => {
    let { questId } = ctx.query;
    // console.log(questId);
    let quest = await Quest.findOne({ where: { id: questId } })
    let url = `http://localhost:3500/quest/writequest/${quest.getDataValue('code')}`
    let img = qr.image(url, { type: 'png' })
    ctx.status = 200;
    ctx.type = 'image/png';
    ctx.body = img;
}


//编辑问卷(评分问卷)
let editQuest_g = async ctx => {

    let { questId } = ctx.query;

    if (!questId) return ctx.body = { err: 99, msg: '参数错误' }

    let obj = await join({
        attributes: ['id', 'questName', 'questTypeId', 'questStateId', 'remarks'],
        where: {
            id: questId
        },
        include: [
            {
                model: Option,
                attributes: ['id', 'content', 'remarks'],
                order: [['id', 'asc']]
            }
        ]
    })

    let result = JSON.parse(JSON.stringify(obj.rows[0]))

    result.options.forEach((item, index) => {
        item.i = index + 1
    })


    ctx.render('createwj.html', result)

}

let editQuest_p = async ctx => {
    let { questId, title, remark, optionArr } = ctx.request.body;


    if (!questId || !title.trim() || optionArr.length === 0) return ctx.body = { code: 443, err: '编辑失败，请输入必要内容' }

    let isExist = await Quest.findOne({ where: { id: questId } })

    if (!isExist) return ctx.body = { err: 60, msg: '错误，不存在问卷' }

    if (isExist.getDataValue('questName') !== title) {
        await Quest.update({ questName: title, createAt: Date.now() }, { where: { id: questId } })
    } else if (isExist.getDataValue('remarks') !== remark) {
        await Quest.update({ remarks: remark, createAt: Date.now() }, { where: { id: questId } })
    }

    await Option.destroy({ where: { questId: questId } })

    let arr = []

    optionArr.forEach(item => {
        let obj = {
            content: item.content,
            questId: questId,
            optionTypeId: 4,
            remarks: item.remark
        }
        arr.push(obj)
    })

    await Option.bulkCreate(arr)

    ctx.body = {
        code: 200,
        msg: '编辑成功'
    }


}

/*编辑页面（普通问卷） 
{
    title: ,
    remark: ,
    list: [{
        id: 0,
        content: '',
        type: this.typeid,
        remark: '',
        options: [{
            id: 1,
            content: ''
        }, {
            id: 2,
            content: ''
        }] 
    }]
}
 */
let editcommonquest_g = async ctx => {
    let { questId } = ctx.query;

    if (!questId) return ctx.body = { err: 99, msg: '参数错误' }

    let obj = await join({
        attributes: ['id', 'questName', 'questTypeId', 'questStateId', 'remarks'],
        where: {
            id: questId
        },
        include: [
            {
                model: Option,
                attributes: ['id', 'content', 'optionTypeId', 'remarks'],
                order: [['id', 'asc']],
                include: [
                    {
                        model: Childoption,
                        attributes: ['id', 'content']
                    }
                ]
            }

        ]
    })

    let questObj = JSON.parse(JSON.stringify(obj.rows[0]))

    let options = []
    questObj.options.forEach((item, index) => {

        let childoptions = []

        item.childoptions.forEach(childitem => {
            childoptions.push({
                id: childitem.id,
                content: childitem.content
            })
        })

        let typeId;
        if (item.optionTypeId === 2) {
            typeId = 1
        } else if (item.optionTypeId === 3) {
            typeId = 2
        } else if (item.optionTypeId === 1) {
            typeId = 3
        }

        options.push({
            id: index + 1,
            content: item.content,
            type: typeId,
            remark: item.remarks,
            options: childoptions
        })

    })

    ctx.body = {
        code: 200,
        data: {
            title: questObj.questName,
            remark: questObj.remarks,
            list: options
        }
    }

}
/* 确定编辑（普通问卷）
{
    questId:this.questId,
    title: this.title,
    remark: this.remark,
    list: this.list
}
*/

let confimeditcommonquest_p = async ctx => {
    let { questId, title, remark, list } = ctx.request.body;


    if (!questId || !title.trim() || list.length === 0) return ctx.body = { code: 443, err: '编辑失败，请输入必要内容' }

    let isExist = await Quest.findOne({ where: { id: questId } })

    if (!isExist) return ctx.body = { err: 60, msg: '错误，不存在问卷' }

    if (isExist.getDataValue('questName') !== title) {
        await Quest.update({ questName: title, createAt: Date.now() }, { where: { id: questId } })
    } else if (isExist.getDataValue('remarks') !== remark) {
        await Quest.update({ remarks: remark, createAt: Date.now() }, { where: { id: questId } })
    }
    let optionObj = await Option.findAll({ where: { questId: questId } })

    let optionArr = []
    JSON.parse(JSON.stringify(optionObj)).forEach(item => {
        optionArr.push(item.id)
    })

    await Childoption.destroy({ where: { optionId: { [Op.in]: optionArr } } })

    await Option.destroy({ where: { questId: questId } })



    //重新插入选项和子选项
    let Options = []

    list.forEach(item => {
        let typeId;
        if (item.type === 1) {
            typeId = 2
        } else if (item.type === 2) {
            typeId = 3
        } else if (item.type === 3) {
            typeId = 1
        }

        let obj = {
            content: item.content,
            questId: questId,
            optionTypeId: typeId,
            remarks: item.remark
        }
        Options.push(obj)
    })

    let parOp = await Option.bulkCreate(Options)


    let childOptions = []
    parOp.forEach((item, index) => {
        item.childlist = list[index].options
    })

    parOp.forEach(item => {

        item.childlist.forEach(child => {
            childOptions.push({
                optionId: item.id,
                content: child.content
            })
        })
    })


    await Childoption.bulkCreate(childOptions);


    ctx.body = { code: 200, msg: 'ok' }

}

//从待发布到发布
let statetran_p = async ctx => {
    let { questId, maxScore, endTime } = ctx.request.body;

    if (!questId) return ctx.body = { err: 24, msg: '错误' }

    let quest = await Quest.findOne({ where: { id: questId } })

    // console.log(quest);
    if (quest) {

        if (quest.getDataValue('questTypeId') === 1) {
            if (!maxScore || Number(maxScore).toString() === 'NaN') return ctx.body = { err: 24, msg: '错误' }
        }

        await Quest.update({ questStateId: 1, createAt: Date.now(), deadline: endTime === null ? null : new Date(endTime).getTime() }, { where: { id: questId } })


        if (quest.getDataValue('questTypeId') === 1) {
            await Scorelimit.create({
                questId: questId,
                score: parseInt(maxScore)
            })

        }


        let obj = await join({
            attributes: ['id', 'code', 'questTypeId', 'questName', 'remarks', 'deadline', 'createAt'],
            where: {
                isDeleted: '0',
                id: questId
            },
            include: [
                {
                    model: Option,
                    attributes: ['id', 'content']
                },
                {
                    model: Userquest,
                    attributes: ['id', 'questId']
                }, {
                    model: Questtype,
                    attributes: ['typeName']
                }
            ],
            order: [['id', 'desc']]
        })
        let list = JSON.parse(JSON.stringify(obj))

        let result = []
        list.rows.forEach(item => {
            result.push({
                id: item.id,
                typeId: item.questTypeId,
                type: item.questtype.typeName,
                title: item.questName,
                remark: item.remarks,
                optionCount: item.options.length,
                writeCount: item.userquests.length,
                state: 1,
                createTime: new Date(parseInt(item.createAt)).get()['date'],
                endTime: item.deadline === null ? null : new Date(parseInt(item.deadline)).get()['date'],
                url: 'http://localhost:3500/quest/writequest/' + item.code
            })
        })


        ctx.body = {
            code: 200,
            msg: '发布成功',
            data: result
        }
    }
    else {
        ctx.body = { err: 56, msg: '错误，发布失败' }
    }
}



//请求问卷页面
let quest_g = async ctx => {


    //获取问卷编号
    let id = ctx.params.id.toString();
    // console.log(id);
    let quest = await Quest.findOne({ where: { code: id } })


    // 判断是否存在该问卷
    if (quest) {

        let isDeleted = quest.getDataValue('isDeleted');
        let stateId = quest.getDataValue('questStateId');
        let endTime = quest.getDataValue('deadline');

        //判断用户是否登录
        if (!ctx.session.username) {
            ctx.session.code = id
            console.log('该用户没有登录，跳转到登录', id);
            return ctx.redirect('/user')
        }

        if (ctx.session.username !== 'admin') {
            // 判断问卷是否删除或者截止时间
            if (isDeleted === '0' && stateId === 1 && endTime === null || endTime > Date.now()) {

                let qu = await Userquest.findOne({
                    where: {
                        userId: ctx.session.id,
                        questId: quest.getDataValue('id')
                    }
                })

                //判断用户是否填写过
                if (qu) {
                    ctx.render('tksquest.html', { title: quest.getDataValue('questName') })
                } else {
                    ctx.render('quest.html')
                }

            } else {
                ctx.render('err.html')
            }
        } else {
            ctx.render('quest.html')
        }



    }
    else {
        ctx.render('err.html')
    }

}
//获取问卷页面数据
let quest_p = async ctx => {

    let { id } = ctx.request.body
    let quest = await Quest.findOne({ where: { code: id } })

    // 判断是否存在该问卷
    if (quest) {
        let isDeleted = quest.getDataValue('isDeleted');
        let endTime = quest.getDataValue('deadline');
        let stateId = quest.getDataValue('questStateId');
        let typeId = quest.getDataValue('questTypeId');


        if (ctx.session.username !== 'admin') {
            // 判断问卷是否删除、开启或者截止时间
            if (isDeleted === '0' && stateId === 1 && endTime === null || endTime > Date.now()) {

                let action = {}

                // 问卷类型，1.打分问卷 2.普通问卷
                if (typeId === 1) {
                    let obj = await join({
                        attributes: ['id', 'code', 'questName', 'questTypeId', 'questStateId', 'remarks'],
                        where: {
                            code: id
                        },
                        include: [
                            {
                                model: Scorelimit,
                                attributes: ['id', 'score']
                            },
                            {
                                model: Option,
                                attributes: ['id', 'content', 'remarks'],
                                order: [['id', 'asc']]
                            }
                        ]
                    })
                    obj = JSON.parse(JSON.stringify(obj)).rows[0]


                    obj.options.forEach(item => {
                        item.value = ''
                    })

                    action = {
                        id: quest.getDataValue('id'),
                        title: obj.questName,
                        remark: obj.remarks,
                        questTp: obj.questTypeId,
                        maxScore: obj.scorelimits[0].score,
                        optionList: obj.options.sort(keySort('id', false))
                    }

                } else {//普通问卷

                    let obj = await join({
                        attributes: ['id', 'questName', 'questTypeId', 'questStateId', 'remarks'],
                        where: {
                            code: id
                        },
                        include: [
                            {
                                model: Option,
                                attributes: ['id', 'content', 'optionTypeId', 'remarks'],
                                order: [['id', 'asc']],
                                include: [
                                    {
                                        model: Childoption,
                                        attributes: ['id', 'content']
                                    }
                                ]
                            }

                        ]
                    })

                    let questObj = JSON.parse(JSON.stringify(obj.rows[0]))
                    // console.log(questObj);
                    let options = []
                    questObj.options.forEach((item, index) => {

                        let childoptions = []

                        item.childoptions.forEach(childitem => {
                            childoptions.push({
                                id: childitem.id,
                                content: childitem.content
                            })
                        })

                        let typeId;
                        if (item.optionTypeId === 2) {
                            typeId = 1
                        } else if (item.optionTypeId === 3) {
                            typeId = 2
                        } else if (item.optionTypeId === 1) {
                            typeId = 3
                        }

                        options.push({
                            id: item.id,
                            content: item.content,
                            type: typeId,
                            value: typeId === 2 ? [] : '',
                            remark: item.remarks,
                            options: childoptions
                        })

                    })
                    action = {
                        id: questObj.id,
                        title: questObj.questName,
                        remark: questObj.remarks,
                        questTp: 2,
                        list: options
                    }

                }

                ctx.body = action
            } else {
                ctx.body = { err: '错误' }
            }
        } else {//管理员可以查看任务问卷
            let action = {}

            // 问卷类型，1.打分问卷 2.普通问卷
            if (typeId === 1) {
                let obj = await join({
                    attributes: ['id', 'code', 'questName', 'questTypeId', 'questStateId', 'remarks'],
                    where: {
                        code: id
                    },
                    include: [
                        {
                            model: Scorelimit,
                            attributes: ['id', 'score']
                        },
                        {
                            model: Option,
                            attributes: ['id', 'content', 'remarks'],
                            order: [['id', 'asc']]
                        }
                    ]
                })
                obj = JSON.parse(JSON.stringify(obj)).rows[0]


                obj.options.forEach(item => {
                    item.value = ''
                })

                action = {
                    id: quest.getDataValue('id'),
                    title: obj.questName,
                    remark: obj.remarks,
                    questTp: obj.questTypeId,
                    maxScore: obj.scorelimits[0].score,
                    optionList: obj.options.sort(keySort('id', false))
                }

            } else {//普通问卷

                let obj = await join({
                    attributes: ['id', 'questName', 'questTypeId', 'questStateId', 'remarks'],
                    where: {
                        code: id
                    },
                    include: [
                        {
                            model: Option,
                            attributes: ['id', 'content', 'optionTypeId', 'remarks'],
                            order: [['id', 'asc']],
                            include: [
                                {
                                    model: Childoption,
                                    attributes: ['id', 'content']
                                }
                            ]
                        }

                    ]
                })

                let questObj = JSON.parse(JSON.stringify(obj.rows[0]))
                // console.log(questObj);
                let options = []
                questObj.options.forEach((item, index) => {

                    let childoptions = []

                    item.childoptions.forEach(childitem => {
                        childoptions.push({
                            id: childitem.id,
                            content: childitem.content
                        })
                    })

                    let typeId;
                    if (item.optionTypeId === 2) {
                        typeId = 1
                    } else if (item.optionTypeId === 3) {
                        typeId = 2
                    } else if (item.optionTypeId === 1) {
                        typeId = 3
                    }

                    options.push({
                        id: item.id,
                        content: item.content,
                        type: typeId,
                        value: typeId === 2 ? [] : '',
                        remark: item.remarks,
                        options: childoptions
                    })

                })
                action = {
                    id: questObj.id,
                    title: questObj.questName,
                    remark: questObj.remarks,
                    questTp: 2,
                    list: options
                }

            }

            ctx.body = action
        }


    }
    else {
        ctx.body = { err: '错误' }
    }

}
//用户提交问卷
let questsubmit_p = async ctx => {
    let { id, optionList } = ctx.request.body;

    if (ctx.session.username === 'admin') return ctx.body = { err: 660, msg: '管理员无法填写问卷，请尝试切换账号' }

    let uq = await Userquest.create({
        userId: ctx.session.id,
        questId: id
    })
    let options = []

    let err = 0
    optionList.forEach(item => {

        options.push({
            userquestId: uq.getDataValue('id'),
            optionId: item.id,
            content: item.value
        })
    })

    if (err !== 0) return ctx.body = { err: 642, msg: '错误，提交失败' }
    // console.log(options);
    await Result.bulkCreate(options)
    ctx.body = { code: 200, msg: '成功' }
}







module.exports = {
    '/': ['get', home_g],
    '/home/admin/center': ['get', adminCenter_g],
    '/home/updateinfo': ['post', uppwdVtr_p],
    '/quest/writequest/:id': ['get', quest_g],
    '/quest/writequest': ['post', quest_p],
    '/quest/usersubmt': ['post', questsubmit_p],
    '/home/quest/startlist': ['get', startQuest_g],
    '/home/quest/stoplist': ['get', stopQuest_g],
    '/home/quest/savelist': ['get', saveQuest_g],
    '/home/variation/svstquest': ['post', statetran_p],
    '/home/editQuest': ['get', editQuest_g],
    '/home/edit/commitquest': ['post', editQuest_p],
    '/home/closequest': ['post', closeQuest_p],
    '/home/deletedquest': ['post', deletedQuest_d],
    '/home/edit/commonquest': ['get', editcommonquest_g],
    '/home/edit/confimcommonquest': ['post', confimeditcommonquest_p],
    '/home/findquest/result': ['get', questdataview_g],
    '/home/createimage': ['get', createImage_g]
}